package com.yl.controller;

import com.yl.model.TShopCoupon;
import com.yl.model.TShopCouponGet;
import com.yl.model.TUser;
import com.yl.result.ResultVO;
import com.yl.service.TShopCouponGetService;
import com.yl.service.TShopCouponService;
import com.yl.service.TUserService;
import com.yl.utils.*;
import com.yl.vo.UserVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wechat")
@Slf4j
public class WechatController {
    @Autowired
    private WxMpService wxMpService;

    @Autowired
    TUserService userService;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    TShopCouponGetService tShopCouponGetService;

    @Autowired
    TShopCouponService tShopCouponService;

    @Value("${wechat.notifyUrl}")
    private String notifyUrl;

    @Value("${wechat.mpAppId}")
    private String mpAppId;

    @Value("${wechat.mpAppSecret}")
    private String mpAppSecret;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @ApiOperation(value = "获取微信openId接口")
    @GetMapping("/authorize")
    public void authorize(@RequestParam("returnUrl") String returnUrl, HttpServletResponse response){
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(notifyUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, returnUrl);
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        try {
            response.sendRedirect(redirectURL);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @GetMapping("/userInfo")
    public void userInfo(@RequestParam("code") String code,
                        @RequestParam("state") String returnUrl,HttpServletResponse response) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        TUser user = userService.findUserByOpenId(openId);
        String token = TokenUtil.generate();
        if(user==null){
            user= new TUser();
            user.setOpenId(openId);
            user.insert();
        }
        UserVo userVo = new UserVo();
        userVo.setUserId(user.getUserId()+"");
        userVo.setOpenId(openId);
        redisUtil.set(token, JsonUtil.parse(userVo), 60*60*24);
        log.info("【微信网页授权】openId={}", openId);
        Map<String,String> map = new HashMap<>();
        map.put("redirect",returnUrl);
        map.put("openId",openId);
        map.put("token",token);
        response.sendRedirect(returnUrl+"?token="+token+"&openId"+openId);
    }


    @ApiOperation(value = "微信授权接口")
    @GetMapping("/wxConfirmOrder")
    public void wxConfirmOrder(HttpServletRequest request, HttpServletResponse response,
                       @RequestParam("action") String action){
        String ip = request.getRequestURL().toString();
        ip = ip.substring(0,ip.lastIndexOf("/"));
        ip = ip.substring(0,ip.lastIndexOf("/"));
        //ip = ip.replace("http:","https:");

        String notifyUrlStr = null;
        String returnUrl = null;
        try {
            //notifyUrlStr = URLEncoder.encode(ip + "/wechat/getWxUserInfo?action=" + action, "UTF-8");
            notifyUrlStr = ip.replace("http:","https:") + "/wechat/getWxUserInfo?action=" + action;
            if(notifyUrl.lastIndexOf(":")>8){
                ip = ip.replace("/yl",notifyUrl.substring(notifyUrl.lastIndexOf(":"),notifyUrl.indexOf("/yl")+3));
            }
            returnUrl = URLEncoder.encode(ip + "/pages/html/goods/confirm_order.html", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        log.info("####  notifyUrlStr = " + notifyUrlStr);
        log.info("####  returnUrl = " + returnUrl);

        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(notifyUrlStr, WxConsts.OAuth2Scope.SNSAPI_USERINFO, returnUrl);
        redirectURL = redirectURL.replace("#wechat_redirect","&connect_redirect=1#wechat_redirect");
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        try {
            response.sendRedirect(redirectURL);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @GetMapping("/getWxUserInfo")
    public void getWxUserInfo(@RequestParam("code") String code,
                         @RequestParam(value="action",required=false) String action,
                              @RequestParam("state") String returnUrl,
                              HttpServletResponse response) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        String unionId = wxMpOAuth2AccessToken.getUnionId();
        String unionIdStr = "";
        if(unionId != null)
            unionIdStr = "&unionId=" + unionId;
        log.info("##### openId = " + openId);
        log.info("##### unionId = " + unionId);
        String token = TokenUtil.generate();
        /*TUser user = userService.findUserByOpenId(openId);
        if(user==null){
            user= new TUser();
            user.setOpenId(openId);
            user.insert();
        }
        UserVo userVo = new UserVo();
        userVo.setUserId(user.getUserId()+"");
        userVo.setOpenId(openId);
        redisUtil.set(token, JsonUtil.parse(userVo), 60*60*24);*/
        log.info("【微信网页授权】openId={}", openId);
        Map<String,String> map = new HashMap<>();
        map.put("redirect",returnUrl);
        map.put("openId",openId);
        map.put("token",token);
        response.sendRedirect(returnUrl+"?token="+token+"&openId="+openId+ unionIdStr + "&action="+action);
    }


    @ApiOperation(value = "我的订单接口")
    @GetMapping("/wxMyOrder")
    public void wxMyOrder(HttpServletRequest request, HttpServletResponse response){
        String ip = request.getRequestURL().toString();
        ip = ip.substring(0,ip.lastIndexOf("/"));
        ip = ip.substring(0,ip.lastIndexOf("/"));
        //ip = ip.replace("http:","https:");
        String notifyUrlStr = null;
        String returnUrl = null;
        try {
            //notifyUrlStr = URLEncoder.encode(ip + "/wechat/getWxUserInfo", "UTF-8");
            notifyUrlStr = ip.replace("http:","https:") + "/wechat/getWxUserInfo";
            if(notifyUrl.lastIndexOf(":")>8){
                ip = ip.replace("/yl",notifyUrl.substring(notifyUrl.lastIndexOf(":"),notifyUrl.indexOf("/yl")+3));
                //log.info("#### ip = " + ip);
            }
            returnUrl = URLEncoder.encode(ip + "/pages/html/index.html", "UTF-8");
            //returnUrl = URLEncoder.encode(ip + "/pages/html/order/my_order.html", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        log.info("####  notifyUrlStr = " + notifyUrlStr);
        log.info("####  returnUrl = " + returnUrl);

        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(notifyUrlStr, WxConsts.OAuth2Scope.SNSAPI_USERINFO, returnUrl);
        redirectURL = redirectURL.replace("#wechat_redirect","&connect_redirect=1#wechat_redirect");
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        try {
            response.sendRedirect(redirectURL);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "微信万达支付页面")
    @GetMapping("/wxWandaOrder")
    public void wxWandaOrder(HttpServletRequest request, HttpServletResponse response,
                               @RequestParam("action") String action){
        String ip = request.getRequestURL().toString();
        ip = ip.substring(0,ip.lastIndexOf("/"));
        ip = ip.substring(0,ip.lastIndexOf("/"));
        //ip = ip.replace("http:","https:");

        String notifyUrlStr = null;
        String returnUrl = null;
        try {
            //notifyUrlStr = URLEncoder.encode(ip + "/wechat/getWxUserInfo?action=" + action, "UTF-8");
            notifyUrlStr = ip.replace("http:","https:") + "/wechat/getWxUserInfo?action=" + action;
            if(notifyUrl.lastIndexOf(":")>8){
                ip = ip.replace("/yl",notifyUrl.substring(notifyUrl.lastIndexOf(":"),notifyUrl.indexOf("/yl")+3));
            }
            if(action.equals("2"))
                returnUrl = URLEncoder.encode(ip + "/pages/html/goods/confirm_wanda_yuxue_order.html", "UTF-8");
            else
                returnUrl = URLEncoder.encode(ip + "/pages/html/goods/confirm_wanda_order.html", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        log.info("####  notifyUrlStr = " + notifyUrlStr);
        log.info("####  returnUrl = " + returnUrl);

        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(notifyUrlStr, WxConsts.OAuth2Scope.SNSAPI_USERINFO, returnUrl);
        redirectURL = redirectURL.replace("#wechat_redirect","&connect_redirect=1#wechat_redirect");
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        try {
            response.sendRedirect(redirectURL);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private TShopCouponGet createTShopCouponGet(String couponId,String openId){
        TShopCoupon shopCoupon = tShopCouponService.findShopCouponById(couponId);
        TShopCouponGet tShopCouponGet = new TShopCouponGet();
        tShopCouponGet.setCouponId(Long.valueOf(couponId));
        tShopCouponGet.setAvailable(1);
        tShopCouponGet.setBalance(shopCoupon.getDiscountAmount());
        tShopCouponGet.setOpenId(openId);
        tShopCouponGet.setReceiveTime(Utils.formatDateTime(sdf.format(new Date())));
        return tShopCouponGetService.createTShopCouponGet(tShopCouponGet);
    }

    @ApiOperation(value = "领取优惠券接口")
    @GetMapping("/gotCoupon")
    public int gotCoupon(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "openId",required=false) String openId,
                             @RequestParam("couponId") String couponId){

        if(openId != null && !openId.trim().equals("")){
            TShopCouponGet get = tShopCouponGetService.findShopCouponGetByOpenIdAndCouponId(openId,couponId);
            if(get == null || get.getCouponPringId() == null){//还未领取
                get = createTShopCouponGet(couponId,openId);
                return 1;
            }else
                return 0;
        }else {
            String ip = request.getRequestURL().toString();
            ip = ip.substring(0, ip.lastIndexOf("/"));
            ip = ip.substring(0, ip.lastIndexOf("/"));
            //ip = ip.replace("http:","https:");

            String notifyUrlStr = null;
            String returnUrl = null;
            notifyUrlStr = ip.replace("http:", "https:") + "/wechat/getWxUserInfoAndDoBusiness?action=getCoupon&id=" + couponId;
            if (notifyUrl.lastIndexOf(":") > 8) {
                ip = ip.replace("/yl", notifyUrl.substring(notifyUrl.lastIndexOf(":"), notifyUrl.indexOf("/yl") + 3));
            }
            log.info("####  notifyUrlStr = " + notifyUrlStr);
            log.info("####  returnUrl = " + returnUrl);

            String redirectURL = wxMpService.oauth2buildAuthorizationUrl(notifyUrlStr, WxConsts.OAuth2Scope.SNSAPI_USERINFO, returnUrl);
            redirectURL = redirectURL.replace("#wechat_redirect", "&connect_redirect=1#wechat_redirect");
            log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
            try {
                response.sendRedirect(redirectURL);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return 1;
    }


    @GetMapping("/getWxUserInfoAndDoBusiness")
    public int getWxUserInfoAndDoBusiness(@RequestParam("code") String code,
                              @RequestParam(value="action") String action,
                              @RequestParam("state") String returnUrl,
                              @RequestParam("id") String id,
                              HttpServletResponse response) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        String unionId = wxMpOAuth2AccessToken.getUnionId();
        String unionIdStr = "";
        if(unionId != null)
            unionIdStr = "&unionId=" + unionId;
        log.info("##### openId = " + openId);
        String token = TokenUtil.generate();
        log.info("【微信网页授权】openId={}", openId);
        log.info("##### CouponId = " + id);

        if(action.equals("getCoupon")){
            TShopCouponGet get = tShopCouponGetService.findShopCouponGetByOpenIdAndCouponId(openId,id);
            if(get == null || get.getCouponPringId() == null){//还未领取
                get = createTShopCouponGet(id,openId);
                return 1;
            }else
                return 0;
        }
        return 1;

        //response.sendRedirect(returnUrl+"?token="+token+"&openId="+openId+ unionIdStr + "&action="+action);
    }

    @GetMapping("/getJSSdk")
    public ResultVO getJSSdk(HttpServletResponse response) throws Exception {
        Object ticket1 = redisUtil.get("xls_ticket");
        String ticket = String.valueOf(ticket1);
        if(ticket1 == null || ticket.equals("")) {
            wxMpService.getWxMpConfigStorage().expireJsapiTicket();
            ticket = wxMpService.getJsapiTicket(true);
            redisUtil.set("xls_ticket", ticket, 6000);
        }
        //log.info("##### ticket = " + ticket);

        String url = "http://xls.chinaesf.net/yl/pages/html/index_mini.html";
        Map<String, String> map = WeiXinUtil.getSdkByJs(url,mpAppId,ticket);
        //Map<String, String> map = WeiXinUtil.getJsSdk(url,mpAppId,mpAppSecret);
        //log.info("##### getJSSdk = " +map);
        return new ResultVO(map);
    }

    @GetMapping("/getGpsLocation")
    public ResultVO getGpsLocation(HttpServletResponse response) throws Exception {
        Object ticket1 = redisUtil.get("xls_ticket");
        //log.info("##### ticket = " + ticket1);
        String ticket = String.valueOf(ticket1);
        if(ticket1 == null || ticket.equals("")) {
            wxMpService.getWxMpConfigStorage().expireJsapiTicket();
            ticket = wxMpService.getJsapiTicket(true);
            redisUtil.set("xls_ticket", ticket, 6000);
        }
        log.info("##### ticket1 = " + ticket1 + "\n##### ticket2 = " + ticket);

        String url = "http://xls.chinaesf.net/yl/pages/html/welcome.html";
        Map<String, String> map = WeiXinUtil.getSdkByJs(url,mpAppId,ticket);
        //Map<String, String> map = WeiXinUtil.getJsSdk(url,mpAppId,mpAppSecret);
        //log.info("##### getGpsLocation = " +map);
        return new ResultVO(map);
    }

}
